
###set working directory in the next line
setwd("") 

library(igraph)
library(sna)
source("http://cneurocvs.rmki.kfki.hu/igraph/plus.R")

dyads<-read.csv("dyads.csv")
edges<-cbind(dyads$ccode1,dyads$ccode2,dyads$year,dyads$y)

years<-unique(dyads$year)
years<-sort(years)
years<-subset(years,years>1949)

#####LOUVAIN DETECTION 
ml<-vector(length=length(years))

### create an adjacency matrix

for (j in 1:length(years)){
year<-years[j]

yearedge <- subset(edges,edges[,3]==year)[,1:2]
x<-as.matrix(subset(edges,edges[,3]==year)[,4])
x<-as.vector(x)

v1<-unique(yearedge[,1])
v2<-unique(yearedge[,2])
v3<-c(v1,v2)
vertices<-unique(v3)
length=length(vertices)

adj<-matrix(nrow=length,ncol=length)

colnames(adj)<-vertices
rownames(adj)<-vertices

middle<-1
after<-length-middle
before<-length-after-middle
total<-0

adj[(middle+1):(middle+after),1]<-x[(total+1):(total+after)]
adj[1,(middle+1):(middle+after)]<-x[(total+1):(total+after)]

for (i in 2:(length-1)){

middle<-middle+1
total<-total+after
after<-length-middle
before<-before+1

adj[(middle+1):(middle+after),i]<-x[(total+1):(total+after)]
adj[i,(middle+1):(middle+after)]<-x[(total+1):(total+after)]
}

###make the graph and simplify it
z<-graph.adjacency(adj, mode=c("undirected"))
z2<-simplify(z)
weights<-subset(x,x>0)
E(z2)$weight<- weights

##keep only largest component
cl <- clusters(z2)
to.keep <- which(cl$membership == which.max(cl$csize))
z3<- induced.subgraph(z2, to.keep)
m<- multilevel.community(z3)
ml[j] <- max(m$modularity)
}

###make the plot

plot(years,ml,pch=19,ylab="",bty="n",
     xlab="",
     cex=1.0)
lines(years,ml)
mtext("Modularity",side=2,line=2.5)
mtext("Year",side=1,line=2.5)

savePlot("Figure 7",type="jpg")

